<template>
	<view class="hotelOrder-card" v-for="(item ,index)  in hotelOrderData" :key="item.order_id" >
		<view class="card-top">
			<view class="card-top-left">
				<text>下单时间：</text>
				<text>{{formatSpecificTime(item.order_create_time)}}</text>
			</view>
			<view class="card-top-right">
				<text v-if="item.state_order==1" style="color: #fc394b;" class="ToBePaid">待支付 {{ item.countdown }}</text>
				<text v-if="item.state_order==2" style="color: #e7a441;" class="ToBePaid">待出行</text>
				<text v-if="item.state_order==3" style="color: #67c23a;" class="order-success">已出行</text>
				<text v-if="item.state_order==4" style="color: #e7a441;" class="Refund">退款中</text>
				<text v-if="item.state_order==5" style="color: #67c23a;" class="order-success">交易完成</text>
				<text v-if="item.state_order==6" style="color: #409eff;" class="Refund-success">退款成功</text>
				<text v-if="item.state_order==7" style="color: #fc394b;" class="Refund-success">拒绝退款</text>
			</view>
		</view>
		<view class="card-content" @click="toHotelOrderDetails(item.order_id)">
			<image class="card-img" :src="imageUrl + item.shop_cover_img" mode="aspectFill"></image>
			<view class="card-content-right">            
				<text class="title">{{item.shop_main_title}} | {{item.order_detail}}</text>
				<text class="travel_date">出行时间：{{formatDate(item.travel_date)}}</text>
				<view class="price-box">
					<text style="margin-right: 10rpx;">实付款</text>
					<text class="price-icon">￥</text>
					<text class="price">{{item.all_cost}}</text>
				</view>
			</view>
		</view>
		<view class="card-bottom">
			<button @click="toHotelOrderDetails(item.order_id)">查看详情</button>
			<button open-type="contact" session-from="userPage">联系客服</button>
			<button v-if="!item.if_state_pay" class="Pay-Now" @click="orderPay(item.order_id)">立即付款</button>
			<button v-if="[3].includes(parseInt(item.state_order))" class="Pay-Now" @click="ConfirmOrder(item.order_id)">确认订单</button>
		</view>
	</view>
</template>

<script setup>
	import {imageUrl} from '@/config/request/request.js'
	import {ref,watchEffect,onMounted,defineEmits} from 'vue';
	import {formatSpecificTime,formatDate} from '@/config/CaDateObject.js'
	// import {onLoad} from '@dcloudio/uni-app';
	import {wechatPay} from '@/config/API/ProductDetails.js'
	import { putOrderConfirm } from '@/config/API/Orders.js';
	
	const hotelOrderData = ref([])
	const openId = ref()
	const porps = defineProps({
		orders: {
			type: Array,
			default: () => [],
		},
		orderType:{
			type:Number,
			default:null
		}
	})
	watchEffect(() => {
		hotelOrderData.value = porps.orders
		console.log('父组porps.orders:', porps.orders);
		console.log('父组porps.orderType:', porps.orderType);
		hotelOrderData.value.forEach(item => {
			if (!item.if_state_pay) {
				startCountdown(item);
			}
		});
	});
	onMounted(() => {
		hotelOrderData.value.forEach(item => {
			if (!item.if_state_pay) {
				startCountdown(item);
			}
		});
	});
	const orderPay = async(orderId) =>{
		openId.value = uni.getStorageSync('userInfo').openID
		const itForm = {
			order_id:orderId,
			openid:openId.value
		}
		try {
			const resPay = await wechatPay(itForm)
			if (resPay.code == 200) {
				// wxPay(resPay.data)
				console.log('resPay.data', resPay.data);
				uni.requestPayment({
					provider: "wxpay",
					...resPay.data,
					success: async (res) => {
						console.log(res);
						uni.hideLoading();
						uni.showToast({
							title: '支付成功',
							icon: 'success',
							duration: 1500
						});
						// 延迟 2 秒后再跳转
						setTimeout(() => {
							toHotelOrderDetails(orderId)
						}, 1000);
					},
					
					fail: (err) => {
						console.log(err);
						// 支付失败后的操作
						// 例如，提示用户支付失败
					
						uni.showToast({
							title: '支付失败，请重试',
							icon: 'error'
						});
						// 隐藏加载提示
						uni.hideLoading();
					},
				});
			} else {
				uni.showToast({
					title: '订单异常',
					icon: 'none'
				})
				// 隐藏加载提示
				uni.hideLoading();
			}
		} catch (e) {
			uni.showToast({
				title: '未知错误请稍后再试 ',
				icon: 'none'
			})
			uni.hideLoading();
		}
	}	
	
	const emit = defineEmits(['refreshOrders']);
	// 用户确认订单
	const ConfirmOrder = async (Orderid) => {
		const userId = uni.getStorageSync('userInfo').id;
		const OrderConfirmForm = {
			order_id: Orderid,
			user_id: userId,
		};
		try {
			const resInfo = await putOrderConfirm(OrderConfirmForm);
			console.log('确认订单返回信息', resInfo);
			if (resInfo.code == 200) {
				// 订单确认后，通知父组件刷新数据
				emit('refreshOrders');
				uni.showToast({
					title: '确认成功，西望期待与你的下次相遇',
					icon: 'none',
					duration: 2000
				});
			} else {
				uni.showToast({
					title: '订单确认失败',
					icon: 'none',
				});
			}
		} catch (error) {
			console.error('确认订单失败', error);
			uni.showToast({
				title: '确认订单失败，请稍后再试',
				icon: 'none',
			});
		}
	};
	// 倒计时函数
	const startCountdown = (item) => {
		console.log('订单创建时间:', item.order_create_time);
		// 使用 Date.parse 来解析 UTC 时间
		const orderTimeUTC = Date.parse(item.order_create_time); 
		console.log('订单创建时间 (UTC 时间戳):', orderTimeUTC);
		const deadline = orderTimeUTC + 30 * 60 * 1000;
		const updateCountdown = () => {
			const nowUTC = Date.now(); 
			// 调整当前时间，加8小时
			const adjustedNow = nowUTC + 8 * 60 * 60 * 1000;

			const remainingTime = deadline - adjustedNow;
			if (remainingTime <= 0) {
				item.countdown = '已过期';
				clearInterval(item.countdownInterval);
			} else {
				const minutes = Math.floor(remainingTime / 1000 / 60); // 计算剩余分钟
				const seconds = Math.floor((remainingTime / 1000) % 60); // 计算剩余秒数
				item.countdown = `${minutes} 分 ${seconds} 秒`;
			}
		};
		// 初始化倒计时
		item.countdownInterval = setInterval(updateCountdown, 1000);
		updateCountdown(); // 立即更新一次
	};

	const toHotelOrderDetails = (id) =>{
		uni.navigateTo({
			url:`/myselfSubpages/order/hotelOrderDetails/hotelOrderDetails?orderId=${id}`
		})
	}
</script>

<style lang="scss" scoped>
	.hotelOrder-card{
		width: 100%;
		min-height: 300rpx;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		margin-bottom: 30rpx;
		.card-top{
			display: flex;
			justify-content: space-between;
			align-items: center;
			text{
				font-size: 22rpx;
				-webkit-box-orient: vertical;
				overflow: hidden;
				text-overflow: ellipsis;
			}
			.card-top-left{
				max-width: 50%;
			}
			.card-top-right{
				max-width: 50%;
				.order-success{
					color: #00e16d;
				}
				.ToBePaid{
					color: #fc394b;
				}
				.Refund{
					color: #FFC107;
				}
				.Refund-success{
					color: #00aaff;
				}
			}
		}

		.card-content{
			display: flex;
			justify-content: space-between;
			align-items: end;
			.card-img{
				min-width: 36%;
				max-width: 36%;
				height: 180rpx;
				border-radius: 10rpx;
			}
			.card-content-right{
				min-width: 56%;
				max-width: 56%;
				height: 180rpx;
				display: flex;
				flex-direction: column;
				gap: 15rpx;
				text{
					display: -webkit-box;
					-webkit-box-orient: vertical;
					text-overflow: ellipsis;
					white-space: pre-wrap;
				}
				.title{
					-webkit-line-clamp: 2;
					font-weight: 600;
					font-size: 28rpx;
				}
				.travel_date{
					-webkit-line-clamp: 1;
					font-size: 26rpx;
					color: #8a8a8a;
				}
				.price-box{
					width: 100%;
					padding:10rpx 20rpx;
					box-sizing: border-box;
					display: flex;
					justify-content: flex-end;
					align-items: flex-end;
					text{
						font-size: 26rpx;
						font-weight: 200;
					}
					.price-icon{
						font-size: 22rpx;
						font-weight: bold;
					}
					.price{
						font-size: 26rpx;
						font-weight: bold;
					}
				}
			}
		}
		.card-bottom{
			width: 100%;
			height: 80rpx;
			display: flex;
			justify-content: flex-end;
			align-items: flex-end;
			gap: 20rpx;
			button {
				width: 150rpx;
				height: 60rpx;
				line-height: 60rpx;
				background-color: transparent;
				padding: 0;
				margin: 0;
				font-size: 26rpx;
				border: 1rpx solid #cccccc;
				&::after {
					border: none;
				}
			}
			.Pay-Now{
				color: #fff;
				background-color: #000;
				border: 1rpx solid #000;
			}
		}
	}
</style>